package com.example.word.controller;

import com.example.word.dto.TemplateDTO;
import com.example.word.enums.FilePathEnum;
import com.example.word.pojo.Template;
import com.example.word.service.RedisService;
import com.example.word.service.TemplateService;
import com.example.word.strategy.context.UploadStrategyContext;
import com.example.word.util.IpUtils;

import com.example.word.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 文件模块
 * @author yuwen
 * @date 2023/4/5
 */
@Api(tags = "文件模块")
@RequestMapping("/file")
@RestController
public class FileController {
    @Autowired
    private UploadStrategyContext uploadStrategyContext;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private RedisService redisService;




    /**
     * 上传测试文档
     * @param
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "上传测试文档")
    @PostMapping("/upFile")
    public Result<?> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        String path = uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.WD.getPath());
        String ipAddress = IpUtils.getIpAddress(request);
        redisService.set(ipAddress + "filePath", path, 50L);
        System.out.println("path = " + path);
        //session.setAttribute(ipAddress + "filePath", path);
        return Result.ok();
    }

    /**
     * 上传模板文档
     * @param session
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "上传模板文档")
    @PostMapping("/upTemplate")
    public Result<?> templateUpload(HttpServletRequest request, HttpSession session, @RequestParam("template") MultipartFile file) throws IOException {
        String path = uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.WD.getPath());
        String ipAddress = IpUtils.getIpAddress(request);
        redisService.set(ipAddress + "templatePath", path, 50L);
        //session.setAttribute(ipAddress + "templatePath",path);
        return Result.ok();
    }


    /**
     * 选择自定义上传模板进行对比
     * @param session
     * @return 对比完成的文件路径
     */
    @ApiOperation(value = "上传模板进行对比")
    @PostMapping("/compareByUpLoad")
    public Result<?> fileCompareByUpload(HttpServletRequest request,HttpSession session){
        String downloadPath = templateService.compareByUpload(request,session);
        return Result.ok(downloadPath);
    }


    /**
     * 选择数据库模板进行对比
     *
     * @param
     * @return 对比完成的文件路径
     */
    @ApiOperation(value = "上传模板进行对比")
    @PostMapping("/compareBySelect")
    public Result<?> fileCompareBySelect(HttpServletRequest request, @RequestParam("fileId") Integer id) throws ExecutionException, InterruptedException {
        String ipAddress = IpUtils.getIpAddress(request);
        String downloadPath = templateService.compareBySelect(request, id);

        return Result.ok(downloadPath);
    }

    /**
     * @param response
     * @功能描述 下载文件:
     */
    @RequestMapping("/download")
    public void download(HttpServletResponse response, String path) {
        try {
            // path是指想要下载的文件的路径

            File file = new File(path);
            // File file = new File("/word_demo/myWord/错误报告.doc");

            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}
